import config from '../../config';

import { gamePoll, gameAnswer } from '../../api/index';

function queryStringify(obj) {
  return Object.keys(obj)
    .map(k => {
      return `${k}=${obj[k]}`;
    })
    .join('&');
}

Page({
  data: {
    imgPrefix: config.IMG_PREFIX,
    percent: 0,
    showGoal: false,
    roomid: null,
    game: {
      current_no: 1,
      id: 317,
      title: '',
      items: ['', '', '', ''],
      leave_num: 0,
      leave_time: 5000,
      select_index: -1,
      out_users: [],
      status: 'answering'
    }
  },

  pollTimeout: null,

  onLoad(options) {
    console.log(options);
    this.setData({
      roomid: options.roomid
    });
    this.poll(options.roomid);
  },

  onUnload() {
    clearTimeout(this.pollTimeout);
  },

  answer(e) {
    // 不要限制重复选择
    // if (this.data.game.select_index !== -1) {
    //   return;
    // }

    let { index } = e.currentTarget.dataset;
    this.setData({
      'game.select_index': index
    });
    gameAnswer({
      data: {
        roomid: this.data.roomid,
        index
      }
    });
  },

  poll(roomid) {
    this.setData({
      'game.leave_time': 0,
      percent: 0
    });
    gamePoll({
      data: {
        roomid
      },
      success: res => {
        let game = res.data.data;
        if (game.status === 'answering') {
          this.setData({
            percent: 100,
            game
          });
          clearTimeout(this.pollTimeout);
          this.pollTimeout = setTimeout(() => {
            this.poll(roomid);
          }, game.leave_time);
          // 揭晓答案
        } else if (game.status === 'reveal') {
          this.setData({
            showGoal: true,
            game
          });
          setTimeout(() => {
            this.setData({
              showGoal: false
            });
            this.poll(roomid);
          }, game.leave_time);
        } else if (game.status === 'fail' || game.status === 'win') {
          wx.redirectTo({
            url: '/pages/result/result?' + queryStringify(game)
          });
        } else {
          console.log('other', game);
        }
      }
    });
  }
});
